const http = require('http')
const path = require('path')
const fs = require('fs')
const mine = require('mime')

const server = http.createServer((req, res) => {
    let filePath = path.resolve(__dirname, path.join('www', req.url))

    if (fs.existsSync(filePath)) {
        const stats = fs.statSync(filePath) // 获取该路径对应的资源

        const isDir = stats.isDirectory() // 判断是否是文件夹
        const { ext } = path.parse(filePath) // 路劲的后缀
       

        if (isDir) {
            filePath = path.join(filePath, 'index.html')
        }

         // ++++++ 获取前端请求头的if-modified-since
         const ifModifiedSince = req.headers['if-modified-since']
         let status = 200
         if (timeStamp && Number(timeStamp) === stats.mtimeMs) { // 资源没变更
            status = 304
         }  

         
         
        if (!isDir && fs.existsSync(filePath)) {
            const content = fs.readFileSync(filePath) // 读取文件
            res.writeHead(status, { 
                'Content-Type': mine.getType(ext),
                'cache-control': 'max-age=86400', // 一天
                // 'last-modified': stats.mtimeMs // 最后修改时间
                'etag': '由文件内容生成的hash'  // 文件指纹
            })
            res.end(content)
        }
        console.log(stats)
    }
})

server.listen(3000, () => {
    console.log('server is running at http://localhost:3000')
})